<!--
 * @description: 
 * @Date: 2022-10-25 22:09:15
 * @LastEditTime: 2022-11-24 22:31:24
-->
<template>
  <div class="noteWindow flex">
    <div class="left">
      <div class="titleTop flex pl-5 items-center">
        <span class="text-2xl">备忘录</span>
        <div class="flex flex-col -space-y-1 ml-3" @click="sortClick">
          <el-icon :class="sort == 'aes' ? 'text-blue-400' : ''">
            <CaretTop />
          </el-icon>
          <el-icon :class="sort == 'desc' ? 'text-blue-400' : ''">
            <CaretBottom />
          </el-icon>
        </div>
        <div class="note-saveText text-lg">
          <span v-show="status">
            <el-icon class="text-blue-400" title="已保存同步">
              <DocumentChecked />
            </el-icon>
          </span>
          <span v-show="!status">
            <el-icon class="text-orange-400" title="未保存">
              <DocumentDelete />
            </el-icon>
          </span>
        </div>
        <div class="note-addicon" @click="addNote">
          <el-icon size="30px" title="添加记事">
            <svg
              width="24"
              height="24"
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M24.0605 10L24.0239 38"
                stroke="#fff"
                stroke-width="4"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M10 24L38 24"
                stroke="#fff"
                stroke-width="4"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </el-icon>
        </div>
      </div>
      <div class="titleScroll">
        <transition v-for="(item, index) in list" :key="item.id">
          <div
            class="noteWindow-list text-black hover:text-blue-500 hover:bg-white"
            :class="{ 'noteWindow-listSelect': item == sp }"
            @click="choose(item)"
          >
            <div class="font-bold text-ellipsis whitespace-nowrap overflow-hidden h-5">
              {{ item.title || "无标题" }}
            </div>
            <div class="text-xs mt-1">{{ formattime(item.update_time) }}</div>
            <div class="note-delicon">
              <el-icon @click.stop="del(item)" title="删除">
                <Delete />
              </el-icon>
            </div>
          </div>
        </transition>
      </div>
    </div>
    <div class="right flex items-center justify-center" v-if="list.length == 0">
      <img :src="empty" class="w-2/3 h-2/3 opacity-80" />
    </div>
    <div class="right" v-else v-loading="load">
      <input
        placeholder="请输入标题"
        v-model="sp.title"
        maxlength="50"
        @keydown="save($event)"
        @input="inp"
        class="text-lg font-bold w-full outline-none border-none placeholder-gray-400"
      />
      <textarea
        placeholder="从这里开始书写您的记录吧"
        class="w-full placeholder-gray-400"
        @keydown="save($event)"
        maxlength="5000"
        v-model="sp.text"
        @input="inp"
      ></textarea>
      <div class="flex mt-1.5">
        <span class="text-xs text-gray-400">
          <span :style="sp.text && sp.text.length == 5000 ? 'color:red' : ''">
            {{ sp.text ? sp.text.length : 0 }}/5000</span
          >
          <span class="ml-2">
            快捷保存Ctrl+S(Mac为 Command+S)。内容传输经过双重加密。
          </span>
        </span>
        <el-button
          size="small"
          class="ml-auto -mt-1.5"
          @click="save($event, true)"
          type="primary"
          >保存</el-button
        >
      </div>
    </div>
  </div>
</template>
<script setup>
import { onUnmounted, ref } from "vue";
import sm from "../../../util/sm2";
import ajax from "../../../util/ajax";
import cache from "../../../util/cache";
import {
  Delete,
  FolderOpened,
  CaretTop,
  CaretBottom,
  DocumentChecked,
  DocumentDelete,
} from "@element-plus/icons-vue";
import moment from "moment";
import empty from "@/assets/svg/empty.svg";
import emitter from "../../../util/emitter";
import { ElMessage, ElMessageBox } from "element-plus";
import store from "../../../util/store";
const status = ref(true);
const load = ref(false);
const sp = ref({
  text: "",
  title: "",
});
const sort = ref(cache.get("noteSort", "desc"));
const sortClick = () => {
  if (sort.value == "desc") {
    sort.value = "aes";
  } else {
    sort.value = "desc";
  }
  cache.set("noteSort", sort.value);
  start();
};
const inp = (text) => {
  status.value = false;
};
const list = ref([]);
const formattime = (t) => {
  return moment(t).format("YYYY/MM/DD HH:mm");
};
const choose = (item) => {
  save({}, true, function () {
    if (item.id == sp.value.id) return;
    sp.value = item;
    if (item.id) {
      load.value = true;
      ajax({
        url: "/note/getText",
        params: { id: item.id },
      })
        .then((_) => {
          try {
            if (_.code == 1) {
              if (_.data.id == sp.value.id) {
                sp.value.text = sm.decode(_.data.text);
              }
            }
          } catch (error) {
            ElMessage.error("获取失败");
          }
        })
        .finally(() => {
          setTimeout(() => {
            load.value = false;
          }, 100);
        });
    }
  });
};
const del = async (item) => {
  const index = list.value.findIndex((i) => i.id == item.id);
  if (index > -1) {
    list.value.splice(index, 1);
    if (item.id) {
      ajax({
        url: "/note/del",
        params: { id: item.id },
      });
    }
  }
  if (index > 0) {
    choose(list.value[index - 1]);
  } else if (list.value.length > 0) {
    choose(list.value[0]);
  } else {
    sp.value = { id: "", title: "", text: "" };
  }
  refreshNote();
};
const refreshNote = () => {
  let dt = [];
  list.value.forEach((el) => {
    if (dt.length < 4) {
      dt.push(Object.assign({}, el));
    }
  });
  emitter.emit("noteLoading", dt);
};

const save = (event, bt = false, next) => {
  const { key = false, ctrlKey = false, metaKey = false } = event;
  if ((key === "s" && (ctrlKey == true || metaKey == true)) || bt) {
    if (!bt) {
      event.preventDefault();
    }
    if (status.value) {
      //如果没有变更则不保存，调用下一步方法
      if (next) {
        next();
      }
      return;
    }
    if (sp.value.text != "" || sp.value.title != "") {
      if (sp.value.title == "") {
        sp.value.title = sp.value.text.slice(0, 49);
      }
      let dt = Object.assign({}, sp.value);
      dt.text = dt.text != "" ? sm.encode(dt.text) : "";
      ajax({
        url: "/note/add",
        method: "post",
        data: {
          ...dt,
        },
      })
        .then((el) => {
          if (el.code == 1) {
            sp.value.id = parseInt(el.data);
            status.value = true;
            refreshNote();
            next && next();
          } else {
            ElMessage.error(el.msg);
          }
        })
        .finally(() => {});
    }
  }
};
const addNote = () => {
  if (store.state.isLogin) {
    let a = {
      id: "",
      title: "",
      text: "",
    };
    list.value.unshift(a);
    choose(list.value[0]);
  } else {
    ElMessage.warning("此功能需要登录才可以用呢");
  }
};
const start = () => {
  ajax({
    url: "/note/get",
    method: "get",
    params: {
      sort: sort.value,
    },
  }).then((el) => {
    list.value = el.data;
    if (list.value.length > 0) {
      choose(list.value[0]);
    }
  });
};
onUnmounted(() => {
  if (status.value == false) {
    save({}, true);
  }
});
start();
</script>
<style lang="less">
:root {
  --noteLeftWidth: 190px;
}

.noteWindow {
  height: 100%;
  width: 100%;

  .note-saveText {
    position: absolute;
    top: 5px;
    right: -30px;
  }

  .note-delicon {
    cursor: pointer;
    height: 17px;
    width: 17px;
    position: absolute;
    top: 5px;
    right: 5px;
    z-index: 10;
    display: none;
  }

  .note-addicon {
    z-index: 9;
    cursor: pointer;
    height: 30px;
    width: 30px;
    border-radius: 30px;
    position: absolute;
    bottom: 10px;
    right: 10px;
    transition: all 0.3s;
    background-color: #60a5fa;

    &:active {
      transform: scale(0.8);
    }
  }

  > .left {
    width: var(--noteLeftWidth);
    height: calc(100% + 28px);
    transform: translateY(-28px);
    background-color: #f9fafb;

    > .titleTop {
      height: 80px;
    }

    > .titleScroll {
      height: calc(100% - 80px);
      overflow-y: scroll;

      > .noteWindow-list {
        position: relative;
        padding: 15px 15px 15px 20px;
        border-bottom: 1px solid rgb(245, 245, 245);
        transition: all 0.3s;

        &:hover {
          .note-delicon {
            display: block;
          }
        }

        &:last-child {
          border-bottom: none;
        }
      }
    }
  }

  > .right {
    width: calc(100% - var(--noteLeftWidth));
    padding: 0px 15px;

    > input {
      height: 35px;
    }

    > textarea {
      height: calc(100% - 75px);
      outline: none;
      border: none;
      resize: none;
    }
  }
}

.noteWindow-listSelect {
  background-color: #fff;

  &::after {
    position: absolute;
    top: 0px;
    left: 0px;
    content: " ";
    width: 5px;
    height: 100%;
    border-radius: 0px 5px 5px 0px;
    background-color: rgba(10, 130, 243, 0.733);
  }
}
</style>
